/*
 * @Description: 封装全局请求方法
 * @Version: //
 * @Autor: syx
 * @Date: 2021-01-04 10:26:35
 * @LastEditors: Hwx
 * @LastEditTime: 2021-08-12 10:53:42
 */
import axiosRequest from "./common-axios"
const GLOBAL_REQUEST_OBJ = {}
function request(name, params) {
  return new Promise((resolve, reject) => {
    if (GLOBAL_REQUEST_OBJ[name] && GLOBAL_REQUEST_OBJ[name] === "requesting") {
      return
    }
    GLOBAL_REQUEST_OBJ[name] = "requesting"
    axiosRequest(params)
      .then(result => {
        delete GLOBAL_REQUEST_OBJ[name]
        resolve(result)
      })
      .catch(err => {
        delete GLOBAL_REQUEST_OBJ[name]
        reject(err)
      })
  })
}

["get", "post"].forEach(type => {
  request[type] = (name, ...params) => {
    return new Promise((resolve, reject) => {
      if (GLOBAL_REQUEST_OBJ[name] && GLOBAL_REQUEST_OBJ[name] === "requesting") {
        return
      }
      GLOBAL_REQUEST_OBJ[name] = "requesting"

      axiosRequest[type]
        .apply(this, params)
        .then(result => {
          delete GLOBAL_REQUEST_OBJ[name]
          resolve(result)
        })
        .catch(err => {
          delete GLOBAL_REQUEST_OBJ[name]
          reject(err)
        })
    })
  }
})

export default request
